package io.wongxd.solution.util

import java.util.concurrent.Callable
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit

object ThreadPoolHelper {

    interface JobExecuteCallback {
        fun onCallback(data: Any)
    }

    val singleJob = Executors.newCachedThreadPool()
    val scheduledJob = Executors.newScheduledThreadPool(2)

    fun executeJob(job: Runnable?) {
        job ?: return
        singleJob.execute(job)
    }

    fun executeCall(job: Callable<Any>?): Any? {
        job ?: return null
        val future = singleJob.submit(job)
        return future.get()
    }

    fun executeScheduleJob(job: Callable<Any>?, callback: JobExecuteCallback?, initialDelay: Long = 0, period: Long = 1000) {
        scheduledJob.scheduleAtFixedRate({
            val result = singleJob.submit(job)
            result ?: return@scheduleAtFixedRate
            callback?.onCallback(result.get())
            if (result.isDone && result.isCancelled.not()) {
                result.cancel(false)
            }
        }, initialDelay, period, TimeUnit.MILLISECONDS)
    }

}